import { Axios } from "axios";

const axios = new Axios({
  method: "get",
});

// -------------------------------功能函数begin--------------------------------------------------------
// 排序函数

function objKeySort(arys) {
  // 先用Object内置类的keys方法获取要排序对象的属性名数组，再利用Array的sort方法进行排序
  const newkey = Object.keys(arys).sort();
  // console.log('newkey=' + newkey);
  let newObj = ""; // 创建一个新的对象，用于存放排好序的键值对
  for (let i = 0; i < newkey.length; i++) {
    // 遍历newkey数组
    newObj += `${[newkey[i]]}=${arys[newkey[i]]}&`;
  }
  return newObj.substring(0, newObj.length - 1);
}

// sha1 运算函数
function add(x, y) {
  return ((x & 0x7fffffff) + (y & 0x7fffffff)) ^ (x & 0x80000000) ^ (y & 0x80000000);
}

function SHA1hex(num) {
  const sHEXChars = "0123456789abcdef";
  let str = "";
  for (let j = 7; j >= 0; j--) str += sHEXChars.charAt((num >> (j * 4)) & 0x0f);
  return str;
}

function AlignSHA1(sIn) {
  const nblk = ((sIn.length + 8) >> 6) + 1;
  const blks = new Array(nblk * 16);
  for (var i = 0; i < nblk * 16; i++) blks[i] = 0;
  for (i = 0; i < sIn.length; i++) blks[i >> 2] |= sIn.charCodeAt(i) << (24 - (i & 3) * 8);
  blks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);
  blks[nblk * 16 - 1] = sIn.length * 8;
  return blks;
}

function rol(num, cnt) {
  return (num << cnt) | (num >>> (32 - cnt));
}

function ft(t, b, c, d) {
  if (t < 20) return (b & c) | (~b & d);
  if (t < 40) return b ^ c ^ d;
  if (t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

function kt(t) {
  return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
}

function SHA1(sIn) {
  const x = AlignSHA1(sIn);
  const w = new Array(80);
  let a = 1732584193;
  let b = -271733879;
  let c = -1732584194;
  let d = 271733878;
  let e = -1009589776;
  for (let i = 0; i < x.length; i += 16) {
    const olda = a;
    const oldb = b;
    const oldc = c;
    const oldd = d;
    const olde = e;
    for (let j = 0; j < 80; j++) {
      if (j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
      const t = add(add(rol(a, 5), ft(j, b, c, d)), add(add(e, w[j]), kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }
    a = add(a, olda);
    b = add(b, oldb);
    c = add(c, oldc);
    d = add(d, oldd);
    e = add(e, olde);
  }
  const SHA1Value = SHA1hex(a) + SHA1hex(b) + SHA1hex(c) + SHA1hex(d) + SHA1hex(e);
  return SHA1Value.toUpperCase();
}

function SHA2(sIn) {
  return SHA1(sIn).toLowerCase();
}

function getQueryVariable(variable) {
  // 获取链接后面的参数和值
  const query = window.location.search.substring(1);
  const vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

// -------------------------------功能函数end--------------------------------------------------------

// -------------------------------业务函数begin--------------------------------------------------------

const URL = "https://sgb-8gqmg7kv48722f4e-1306391227.ap-shanghai.app.tcloudbase.com/test-dev/ticket";

function wxSDK() {
  return new Promise((resolve) => {
    axios.get(URL).then((data) => {
      const o = JSON.parse(data.data).ticket;
      resolve(o);
    });
  });
}

export async function SDKyanzheng() {
  // 微信验证
  const jsapi_ticket = await wxSDK();
  const nonceStr = "Wm3WZYTPz0wzccnW";
  const ts = Math.round(new Date().getTime() / 1000).toString();
  const url = window.location.href;
  const string1 = `jsapi_ticket=${jsapi_ticket}&noncestr=${nonceStr}&timestamp=${ts}&url=${url}`;
  const data = {
    jsapi_ticket,
    noncestr: nonceStr,
    timestamp: ts,
    url,
  };
  const signature = SHA1(objKeySort(data));

  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: "wxb8513069f2775c8d", // 必填，公众号的唯一标识 wxb8513069f2775c8d
    timestamp: ts, // 必填，生成签名的时间戳
    nonceStr, // 必填，生成签名的随机串
    signature, // 必填，签名
    jsApiList: ["updateTimelineShareData", "updateAppMessageShareData"], // 必填，需要使用的JS接口列表
    openTagList: ["wx-open-audio"],
  });

  wx.error((res) => {
    console.log("验证失败");
  });

  return true;
}

export function fenxiang(title, link, imgUrl, desc = "我的24 CH24 现场24") {
  // 设置分享朋友圈和微信朋友功能
  return new Promise((resolve) => {
    wx.ready(() => {
      wx.updateTimelineShareData({
        title, // 分享标题
        link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        success() {
          // 设置成功
          resolve(true);
        },
      });

      wx.updateAppMessageShareData({
        desc, // 分享描述
        title, // 分享标题
        link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        success() {
          // 设置成功
          resolve(true);
        },
      });
    });
  });
}

// -------------------------------业务函数end--------------------------------------------------------
